package com.atguigu.redis.controller;

import com.atguigu.redis.config.RedisUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class GoodController {
    public static final String REDIS_LOCK = "atguiguLock";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Redisson redisson;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/buy_goods")
    public String buy_goods() throws Exception {
        //String value = UUID.randomUUID().toString() + Thread.currentThread().getName();
        RLock rLock = redisson.getLock(REDIS_LOCK);
        rLock.lock();
        try {
            String result = stringRedisTemplate.opsForValue().get("goods:001");
            int goodNumber = result == null ? 0 : Integer.parseInt(result);
            if (goodNumber > 0) {
                int realNumber = goodNumber - 1;
                stringRedisTemplate.opsForValue().set("goods:001", String.valueOf(realNumber));
                stringRedisTemplate.delete(REDIS_LOCK);
                return "成功购买商品,库存还剩下：" + realNumber + "件" + "提供端口" + serverPort;
            } else {
                return "卖完了";
            }
        }finally {
            //是否持有锁并且是当前线程持有
            if (rLock.isLocked()&&rLock.isHeldByCurrentThread()){
                    rLock.unlock();
            }

        }
    }

    public static void main(String[] args) {
        HashMap<Object, Integer> map = new HashMap<>();
        Person person = new Person("aa", 23);
        map.put(person, 3);
        person.setName("bb");
        Integer integer = map.get(person);
        System.out.println(integer);
    }

}
